package com.bwie.gateway.config;

import com.bwie.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.security.auth.login.CredentialNotFoundException;

@Component
public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取访问路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        //放行登录
        if (path.contains("auth.findhouse.com/admin")) {
            return chain.filter(exchange);
        }
        //jwt
        String token = request.getHeaders().get("token").get(0);
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null){
                return chain.filter(exchange);
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
